package cn.wolfcode.wolf2world.web.listener;

import cn.wolfcode.wolf2world.domain.Strategy;
import cn.wolfcode.wolf2world.domain.UserStrategyFavoer;
import cn.wolfcode.wolf2world.redis.service.StaticRedisService;
import cn.wolfcode.wolf2world.redis.service.UserRedisService;
import cn.wolfcode.wolf2world.service.StrategyService;
import cn.wolfcode.wolf2world.service.UserStrategyFavoerService;
import cn.wolfcode.wolf2world.vo.StaticRedisVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/17 22:28
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private StrategyService strategyService;
    @Autowired
    private StaticRedisService staticRedisService;
    @Autowired
    private UserStrategyFavoerService userStrategyFavoerService;
    @Autowired
    private UserRedisService userRedisService;

    //监听spring启动并初始化完成执行
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("--------------redis开始初始化攻略统计数据---------------");
        //获取所有的攻略数据
        List<Strategy> strategies = strategyService.list();
        StaticRedisVO vo = new StaticRedisVO();
        //遍历
        for (Strategy strategy : strategies) {
            if (staticRedisService.hasKey(strategy.getId())) {
                //redis存在数据，不更新，直接跳过
                continue;
            }
            //数据设置到vo对象
            BeanUtils.copyProperties(strategy,vo);
            vo.setSid(strategy.getId());
            //保存到redis中
            staticRedisService.setStaticRedisVO(vo);
        }

        System.out.println("--------------redis初始化攻略统计数据完毕---------------");

        System.out.println("---------------用户攻略开始初始化-----------------------");
        List<UserStrategyFavoer> list = userStrategyFavoerService.list();
        if (list != null && list.size() > 0) {
            for (UserStrategyFavoer userStrategyFavoer : list) {
                //判断key是否存在
                if (userRedisService.hasKey(userStrategyFavoer.getId())) {
                    //存在key，跳过
                    continue;
                }
                //保存到redis中
                userRedisService.setUserStrategyFavor(userStrategyFavoer);
            }
        }
        System.out.println("---------------用户攻略初始化结束-----------------------");
    }
}
